//
//  NBCURLNavgation.m
//  NBCURLRouterDemo
//
//  Created by naruto on 16/8/17.
//  Copyright © 2016年 naruto. All rights reserved.
//

#import "NBCURLNavgation.h"
#import "UIViewController+NBCURLRouter.h"
#import "NBCURLPageModel.h"

@interface NBCURLNavgation()

@end

@implementation NBCURLNavgation

#pragma mark - push vc
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated replace:(BOOL)replace
{
    if (viewController){
        if([viewController isKindOfClass:[UINavigationController class]]) {
            [UIApplication sharedApplication].delegate.window.rootViewController = viewController;
        } // 如果是导航控制器直接设置为根控制器
        else {
            UINavigationController *navigationController = self.currentNavigationViewController;
            if (navigationController) { // 导航控制器存在
                // In case it should replace, look for the last UIViewController on the UINavigationController, if it's of the same class, replace it with a new one.
                if (replace && [navigationController.viewControllers.lastObject isKindOfClass:[viewController class]]) {
                                        
                    NSArray *viewControllers = [navigationController.viewControllers subarrayWithRange:NSMakeRange(0, navigationController.viewControllers.count-1)];
                    [navigationController setViewControllers:[viewControllers arrayByAddingObject:viewController] animated:animated];
                } // 切换当前导航控制器 需要把原来的子控制器都取出来重新添加
                else {
                    [navigationController pushViewController:viewController animated:animated];
                } // 进行push
            }
            else {
                navigationController = [[UINavigationController alloc]initWithRootViewController:viewController];
                [UIApplication sharedApplication].delegate.window.rootViewController = navigationController;
            } // 如果导航控制器不存在,就会创建一个新的,设置为根控制器
        }
    }
}

#pragma mark - present vc
- (void)presentViewController:(UIViewController *)viewController animated: (BOOL)animated completion:(void (^ __nullable)(void))completion
{
    if (viewController) {
        UIViewController *currentViewController = [self currentViewController];
        if (currentViewController) { // 当前控制器存在
            [currentViewController presentViewController:viewController animated:animated completion:completion];
        }
        else { // 将控制器设置为根控制器
            [UIApplication sharedApplication].delegate.window.rootViewController = viewController;
        }
    }
}




#pragma mark - pop vc
- (void)popViewControllerAnimated:(BOOL)animated
{
    [self popViewControllerWithTimes:1 animated:YES];
}
- (void)popToRootViewControllerAnimated:(BOOL)animated
{
    UIViewController *currentViewController = [self currentViewController];
    NSUInteger count = currentViewController.navigationController.viewControllers.count;
    [self popViewControllerWithTimes:count-1 animated:YES];
}

- (void)popViewControllerWithTimes:(NSUInteger)times animated:(BOOL)animated
{
    UIViewController *currentViewController = [self currentViewController];
    NSUInteger count = currentViewController.navigationController.viewControllers.count;
    if(currentViewController.navigationController){
        if (count > times){
            [currentViewController.navigationController popToViewController:[currentViewController.navigationController.viewControllers objectAtIndex:count-1-times] animated:animated];
        }
        else { // 如果times大于控制器的数量
            
        }
    }
}

#pragma mark - dismiss vc
- (void)dismissToRootViewControllerAnimated: (BOOL)animated completion: (void (^ __nullable)(void))completion
{
    UIViewController *currentViewController = [self currentViewController];
    UIViewController *rootVC = currentViewController;
    while (rootVC.presentingViewController) {
        rootVC = rootVC.presentingViewController;
    }
    [rootVC dismissViewControllerAnimated:animated completion:completion];
}
- (void)dismissViewControllerWithTimes:(NSUInteger)times animated: (BOOL)animated completion: (void (^ __nullable)(void))completion
{
    UIViewController *rootVC = [self currentViewController];
    if (rootVC) {
        while (times > 0) {
            rootVC = rootVC.presentingViewController;
            times -= 1;
        }
        [rootVC dismissViewControllerAnimated:YES completion:completion];
    }
    
    if (!rootVC.presentedViewController) {
    }
}



#pragma mark - 获取当前vc 、当前 navgation controller

- (UIViewController *)currentViewController
{
    UIViewController* rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    return [self currentViewControllerFrom:rootViewController];
}

- (UINavigationController *)currentNavigationViewController
{
    UIViewController* currentViewController = self.currentViewController;
    return currentViewController.navigationController;
}

- (UIViewController*)currentViewControllerFrom:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController *)viewController;
        return [self currentViewControllerFrom:navigationController.viewControllers.lastObject];
    } // 如果传入的控制器是导航控制器,则返回最后一个
    else if([viewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController *)viewController;
        return [self currentViewControllerFrom:tabBarController.selectedViewController];
    } // 如果传入的控制器是tabBar控制器,则返回选中的那个
    else if(viewController.presentedViewController != nil) {
        return [self currentViewControllerFrom:viewController.presentedViewController];
    } // 如果传入的控制器发生了modal,则就可以拿到modal的那个控制器
    else {
        return viewController;
    }
}


#pragma mark - vc help
- (UIViewController *)setupFromString:(NSString *)urlString fromConfig:(NSMutableArray<NBCURLPageModel *> *)routeConfig
{
    // 支持对中文字符的编码
    NSString *encodeStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return [self setupFromURL:encodeStr withQuery:nil fromConfig:routeConfig];
}

- (UIViewController *)setupFromString:(NSString *)urlString withQuery:(NSDictionary *)query fromConfig:(NSMutableArray<NBCURLPageModel *> *)routeConfig
{
    // 支持对中文字符的编码
    NSString *encodeStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return [self setupFromURL:encodeStr withQuery:query fromConfig:routeConfig];
}

- (UIViewController *)setupFromURL:(NSString *)urlString withQuery:(NSDictionary *)query fromConfig:(NSMutableArray<NBCURLPageModel *> *)routeConfig
{
    if(urlString.length==0){
        return nil;
    }
    UIViewController *vcDest = nil;
    NSString *pageSpace = nil;
    NSString *pageSchemeParams = nil;//scheme+参数
    NSString *pageScheme = nil;//scheme
    __block Class pageClass = nil;//查找page 配置表找到的class
    NSString *pageParams = nil;
    
    //计算 pageSpace ，先判断url 是否包含 ://
    if(![urlString containsString:@"://"]){
        pageSpace = kNBCURLPageModel_DefaultSpace;
        pageSchemeParams = urlString;
    }
    else{
        NSArray *listURLP1 = [urlString componentsSeparatedByString:@"://"];
        if(listURLP1.count<2){
            return nil;
        }
        pageSpace = listURLP1[0];
        pageSchemeParams = listURLP1[1];
    }
    //计算 pageScheme
    if(![pageSchemeParams containsString:@"?"]){
        pageScheme = pageSchemeParams;
        pageParams = nil;
    }
    else{
        //如果包含 ？
        NSArray *listURLP2 = [pageSchemeParams componentsSeparatedByString:@"?"];
        if(listURLP2.count<2){
            return nil;
        }
        pageScheme = listURLP2[0];
        pageParams = listURLP2[1];
    }

    //开始遍历 scheme 配置表
    [routeConfig enumerateObjectsUsingBlock:^(NBCURLPageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.scheme isEqualToString:pageScheme] && [obj.pageSpace isEqualToString:pageSpace]){
            pageClass = NSClassFromString(obj.pageClass);
            *stop = YES;
        }
    }];
    if(!pageClass){
        return nil;
    }
    vcDest = [[pageClass alloc] init];
    //设置 vc 跳转参数
    if (query) {   // 如果自定义url后面有拼接参数,而且又通过query传入了参数,那么优先query传入了参数
        vcDest.nbcRouterParams = query;
    }
    else if(pageParams.length>0){
        if([vcDest nbcConvertParamsToDict]){
            vcDest.nbcRouterParams = [self paramsURLToDict:pageParams];
        }
        else{
            vcDest.nbcRouterStrParams = pageParams;
        }
        
    }
    return vcDest;
}


/**
 将url的参数部分转化成字典

 @param url url参数
 @return NSDictionary
 */
- (NSDictionary *)paramsURLToDict:(NSString *)urlString
{
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&"];
    NSScanner* scanner = [[NSScanner alloc] initWithString:urlString];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0] stringByRemovingPercentEncoding];
            NSString* value = [[kvPair objectAtIndex:1] stringByRemovingPercentEncoding];
            [pairs setValue:value forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:pairs];
}


@end
